class Solution:
    def removeDuplicateLetters(self, s: str) -> str:
        # 统计每个字符的频率
        count = {}
        for char in s:
            count[char] = count.get(char, 0) + 1
        
        stack = []
        visited = set()
        
        for char in s:
            # 每处理一个字符，减少其频率
            count[char] -= 1
            
            # 如果字符已经在栈中，跳过
            if char in visited:
                continue
            
            # 当栈不为空，且当前字符小于栈顶字符，且栈顶字符后面还会出现
            while stack and char < stack[-1] and count[stack[-1]] > 0:
                # 弹出栈顶字符，并从visited中移除
                removed_char = stack.pop()
                visited.remove(removed_char)
            
            # 将当前字符压入栈中，并标记为已访问
            stack.append(char)
            visited.add(char)
        
        # 将栈中的字符拼接成结果
        return ''.join(stack)

# 测试
solution = Solution()
print(solution.removeDuplicateLetters("bcabc"))      # 输出: "abc"
print(solution.removeDuplicateLetters("cbacdcbc"))   # 输出: "acdb"
print(solution.removeDuplicateLetters("bbcaac"))     # 输出: "bac"
print(solution.removeDuplicateLetters("abcd"))       # 输出: "abcd"
print(solution.removeDuplicateLetters("aaabbb"))     # 输出: "ab"